package com.rr.frame.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.rr.frame.common.FinalDes;
import com.rr.frame.common.JWTHelper;
import com.sun.tools.hat.internal.server.FinalizerObjectsQuery;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;

public class JwtAuthTokenFilter implements Filter{
	
	private static PrintWriter out = null;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("==>JwtAuthTokenFilterFilter启动");
	}
 
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		System.out.println("==>JwtAuthTokenFilter拦截请求");
		JSONObject errorJson = null;
		
		final HttpServletRequest req = (HttpServletRequest) request;
        final String authHeader = req.getHeader("Authorization");
        try {
        	final Claims claims = JWTHelper.parseJWT(authHeader);
        	request.setAttribute("claims", claims);
        }
        catch (final SignatureException e) {
        	e.printStackTrace();
        	errorJson = new JSONObject();
        	//throw new ServletException("Invalid token.");
        	errorJson.put(FinalDes.STATUS_CODE, FinalDes.FA_FAILED_CODE);
        	errorJson.put(FinalDes.STATUS_MSG, "token不合法. ");
            
        }
        catch (final ExpiredJwtException e){
        	e.printStackTrace();
        	errorJson = new JSONObject();
        	//throw new ServletException("Invalid token.");
        	errorJson.put(FinalDes.STATUS_CODE, FinalDes.FA_FAILED_CODE);
        	errorJson.put(FinalDes.STATUS_MSG, "token超时. ");
        }
        catch (Exception e) {
        	e.printStackTrace();
        	errorJson = new JSONObject();
        	//throw new ServletException("Invalid token.");
        	errorJson.put(FinalDes.STATUS_CODE, FinalDes.FA_FAILED_CODE);
        	errorJson.put(FinalDes.STATUS_MSG, e.getMessage());
		}
        
        if(null != errorJson){
        	try{
        		response.setCharacterEncoding("UTF-8");  
        	    response.setContentType("application/json; charset=utf-8");  
        		out = response.getWriter();
        		out.write(errorJson.toString());
        		out.flush();
        	}
        	catch (Exception e) {
				e.printStackTrace();
			}
        	finally {
				if (out != null) {
					out.close();
				}
			}
        	return;
        }
        
        
		chain.doFilter(request, response);
		
	}
 
	@Override
	public void destroy() {
		
	}

}
